<template>
  <el-dialog
    v-toggle-full
    class="base-dialog"
    :class="{ readonly: readOnly }"
    :custom-class="'panna-dialog_big'"
    :title="title"
    :visible.sync="dialogVisible"
    :append-to-body="true"
    :before-close="handleClose"
    @closed="closedDialog"
  >
    <p slot="title">{{ title }}</p>
    <el-form
      ref="formData"
      :model="formData"
      label-width="130px"
      :rules="formRules"
      status-icon
    >
      <el-row>
        <el-col :span="16">
          <el-form-item label="委托类型：" prop="entrustDomain">
            <el-select
              v-model="formData.entrustDomain"
              style="width: 260px"
              :disabled="readOnly"
              @change="entrustDomainChange"
            >
              <el-option
                v-for="items in entrustDomainData"
                :key="items.value"
                :label="items.name"
                :value="Number(items.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <span>{{ formData.orderNum }}</span>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <span style="font-size: 21px; font-weight: bold">委托方信息</span>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :span="11">
          <el-form-item label="单位名称：" prop="customerName">
            <el-input
              v-model="formData.customerName"
              :disabled="true"
              placeholder="请输入单位名称"
              style="width: 100%"
            />
            <div class="addCustomer" @click="AddCustomer">+</div>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="单位地址：" prop="customerAddress">
            <el-input v-model="formData.customerAddress" :disabled="readOnly" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="委托人：" prop="entrustPeople">
            <el-input v-model="formData.entrustPeople" :disabled="readOnly" />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="电话：" prop="phone">
            <el-input v-model="formData.phone" :disabled="readOnly" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="formData.email" :disabled="readOnly" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col>
          <span style="color: red">*</span>
          <span style="font-size: 21px; font-weight: bold">样品检测详情</span>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <EntrustSampleDetection
          ref="EntrustSampleDetection"
          :read-only.sync="readOnly"
          :system-type.sync="systemType"
        />
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col>
          <span style="font-size: 21px; font-weight: bold">委托服务详情</span>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :span="24">
          <el-form-item label="委托取样：" prop="entrustSampleType">
            <el-radio-group
              v-model="formData.entrustSampleType"
              :disabled="readOnly"
            >
              <el-radio
                v-for="(item, index) in entrustSampleTypeList"
                :key="index"
                :label="item.value"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
            <el-input
              v-model="formData.entrustSampleAddress"
              style="width: 30%"
              :disabled="formData.entrustSampleType != 1 || readOnly"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="报告领取方式：" prop="reportGetType">
            <el-radio-group
              v-model="formData.reportGetType"
              :disabled="readOnly"
            >
              <el-radio
                v-for="(item, index) in reportGetTypeList"
                :key="index"
                :label="item.value"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
            <el-input
              v-model="formData.reportGetTypeRemake"
              style="width: 30%"
              :disabled="formData.reportGetType != 3 || readOnly"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="报告是否评价："
            prop="evaluateState"
            style="width: 100%"
          >
            <el-radio-group
              v-model="formData.evaluateState"
              :disabled="readOnly"
            >
              <el-radio
                v-for="(item, index) in reportConclusionTypeData"
                :key="index"
                :label="Number(item.value)"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="样品处置：" prop="sampleDispose">
            <el-radio-group
              v-model="formData.sampleDispose"
              :disabled="readOnly"
            >
              <el-radio
                v-for="(item, index) in sampleDisposeList"
                :key="index"
                :label="item.value"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="报告形式：" prop="reportType">
            <el-radio-group v-model="formData.reportType" :disabled="readOnly">
              <el-radio
                v-for="(item, index) in reportTypeList"
                :key="index"
                :label="item.value"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="报告份数：" prop="reportCount">
            <el-input
              v-model="formData.reportCount"
              :disabled="readOnly"
              style="width: 30%"
            />
            <span>份</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="报告领取时间：" prop="reportGetDateTime">
            <el-date-picker
              v-model="formData.reportGetDateTime"
              type="datetime"
              placeholder="报告领取时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :disabled="readOnly"
              style="width: 30%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="取样地点：" prop="sampleAddress">
            <el-input
              v-model="formData.sampleAddress"
              :disabled="readOnly"
              style="width: 30%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="包装容器：" prop="packageContainer">
            <el-input
              v-model="formData.packageContainer"
              :disabled="readOnly"
              style="width: 30%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="包装状态：" prop="packageStatus">
            <el-radio-group
              v-model="formData.packageStatus"
              :disabled="readOnly"
            >
              <el-radio
                v-for="(item, index) in packageStatusList"
                :key="index"
                :label="item.value"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
            <el-input
              v-model="formData.packageStatusRemake"
              style="width: 30%"
              :disabled="formData.packageStatus != 3 || readOnly"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注：" prop="remake">
            <el-input
              v-model="formData.remake"
              type="textarea"
              :disabled="readOnly"
              placeholder="请输入备注"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span v-if="!readOnly" slot="footer" class="base-dialog-footer">
      <el-button
        v-if="editId"
        :disabled="!submitLoad"
        type="primary"
        @click="submitForm(20, true)"
        >提 交</el-button
      >
      <el-button
        v-if="!editId"
        :disabled="!submitLoad"
        type="primary"
        @click="submitForm(20, false)"
        >提 交</el-button
      >
      <el-button
        :disabled="!submitLoad"
        style="width: 100px"
        type="primary"
        @click="submitForm(0, false)"
        >保 存 草 稿</el-button
      >
      <el-button @click="handleClose">取 消</el-button>
    </span>
    <ChoiceCustomerDialog
      v-model="dialogCustomer"
      @customerClose="customerClose"
    />
    <ChoiceDetectionItemDialog
      ref="ChoiceDetectionItemDialog"
      v-model="dialogDetectionItem"
      :generate-button-state="true"
      :edit-state="editState"
      @DetectionItemClose="DetectionItemClose"
    />
    <PreviewFileDialog
      v-if="previewFileShow"
      :preview-file-show.sync="previewFileShow"
      :preview-file="filepreview"
    />
  </el-dialog>
</template>
<script>
import { getDictList, getConfigByKey } from "../../../api/System/SystemDict.js";
import ChoiceCustomerDialog from "../EntrustOrder/ChoiceCustomerDialog.vue";
import EntrustSampleDetection from "../../../components/EntrustManage/EntrustSampleDetection.vue";

import {
  Create,
  Get,
  Update,
  GetOrderNumber,
} from "../../../api/EntrustManage/EntrustOrder.js";
import PreviewFileDialog from "./PreviewFileDialog.vue";
import _ from "lodash";
export default {
  name: "EntrustOrderDialog",
  components: {
    ChoiceCustomerDialog,
    PreviewFileDialog,
    EntrustSampleDetection,
  },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      showFieldLabel: true,
      systemType: "",
      entrustDomainData: [],
      reportConclusionTypeData: [],
      previewFileShow: false,
      filepreview: {
        fileName: "",
        url: "",
      },
      title: "",
      // 客户弹窗
      dialogCustomer: false,
      // 检测项目弹窗
      dialogDetectionItem: false,
      dialogVisible: false,
      submitLoad: true,
      disabled: false,
      deleteTables: [],
      // 提交的表单数据
      formData: {
        // 样品类别id
        sampleCategoryIdList: [],
        // 委托领域
        entrustDomain: "",
        id: "",
        // 编号规则
        orderNum: "",
        // 客户id
        customerId: 0,
        // 客户名称
        customerName: "",
        // 客户地址
        customerAddress: "",
        // 委托人
        entrustPeople: "",
        // 委托取样地址
        entrustSampleAddress: "",
        // 电话
        phone: "",
        // 邮箱
        email: "",
        // 委托取样类型
        entrustSampleType: 0,
        // 报告领取方式
        reportGetType: 0,
        // 报告领取方式备注
        reportGetTypeRemake: "",
        // 样品处置
        sampleDispose: 0,
        // 报告形式
        reportType: 0,
        // 报告份数
        reportCount: 0,
        // 报告领取时间
        reportGetDateTime: null,
        // 取样地点
        sampleAddress: "",
        // 包装容器
        packageContainer: "",
        // 包装状态
        packageStatus: 0,
        // 包装状态备注
        packageStatusRemake: "",
        // 备注
        remake: "",
        // 委托单状态
        orderStatusCode: -1,
        // 接收人
        receivePeople: "",
        // 检测样品数据
        entrustSampleDetections: [],
        // 检测样品集合
        sampleList: [],
        // 是否评价
        evaluateState: 0,
        isEdit: false,
      },
      formRules: {},
      // 字典数据
      // 报告形式
      reportTypeList: [],
      // 包装状态
      packageStatusList: [],
      // 样品处置
      sampleDisposeList: [],
      // 报告领取方式
      reportGetTypeList: [],
      // 委托取样
      entrustSampleTypeList: [],
      // 是否是编辑的状态
      editState: false,
      getOrderNumberDto: {
        entrustDomain: 0,
        sampleCategoryIdList: [],
        checkOutCategory: 0,
        state: false, // 不修改数据状态false
      },
    };
  },
  watch: {},
  created() {
    this.dialogVisible = this.dialogFormVisible;
    // 查询字典表判断系统类型
    getConfigByKey("SystemType").then((res) => {
      this.systemType = res.data[0].value;
    });
    this.init();
  },

  methods: {
    // 选择委托领域
    entrustDomainChange() {
      this.getOrderNumberDto.entrustDomain = this.formData.entrustDomain;
      this.OrderNumber();
    },
    // 样品类别发生变化
    sampleCategoryChange(sampleCategoryIdList) {
      this.getOrderNumberDto.sampleCategoryIdList = sampleCategoryIdList;
      this.formData.sampleCategoryIdList = sampleCategoryIdList;
      this.OrderNumber();
    },
    OrderNumber() {
      GetOrderNumber(this.getOrderNumberDto).then((res) => {
        this.formData.orderNum = res.data;
      });
    },
    // 编辑重新选择检测项目
    editSampleDetection() {
      if (this.deleteTables.length === 0 || this.deleteTables === null) {
        this.$message.warning("请选择数据!");
        return false;
      }
      if (this.deleteTables.length > 1) {
        this.$message.warning("最多选择一条数据!");
        return false;
      }

      // 选择检测项目中的样品检测项目赋值
      this.$refs.ChoiceDetectionItemDialog.sampleDeteciontItemData.push(
        this.deleteTables[0]
      );
      // 选择的检测项目表赋值检测项目
      this.$refs.ChoiceDetectionItemDialog.selectedTableData =
        this.deleteTables[0].detectionItemData;

      // 点击树获取的样品检测内容暂存 样品类别id,样品类别名称赋值
      this.$refs.ChoiceDetectionItemDialog.choiceSampleMaggess = {
        id: this.deleteTables[0].sysBusinessSampleCategoryId,
        sampleCategoryName: this.deleteTables[0].sampleTypeName,
      };
      this.editState = true;
      this.dialogDetectionItem = true;
    },
    // 检测项目标准方法改变触发事件
    detectionChange(row, index) {
      this.formData.entrustSampleDetections[index].detectionItemName =
        row.detectionItemNameShow;
      this.formData.entrustSampleDetections[index].detectionMethod =
        row.detectionMethodShow;
      this.formData.entrustSampleDetections[index].criterion =
        row.criterionShow;
    },
    // 客户信息弹窗关闭
    customerClose(value) {
      this.formData.customerId = value.id;
      this.formData.customerName = value.customerName;
      this.formData.customerAddress = value.address;

      if (value.sysBusinessCustomerPerson !== null) {
        this.formData.entrustPeople =
          value.sysBusinessCustomerPerson.customerPersonName;
        this.formData.phone = value.sysBusinessCustomerPerson.mobilePhone;
        this.formData.email = value.sysBusinessCustomerPerson.email;
      }
    },
    // 关闭选择检测项目触发事件
    DetectionItemClose(data, fileId) {
      for (let i = 0; i < data.length; i++) {
        data[i].id = data[i].sysBusinessSampleCategoryId;
        if (this.formData.entrustSampleDetections[0] != null) {
          data[i].index =
            this.formData.entrustSampleDetections[
              this.formData.entrustSampleDetections.length - 1
            ].index + 1;
        } else {
          data[i].index = 0;
        }
        this.formData.entrustSampleDetections.push(data[i]);
      }
    },
    // 判断输入内容
    blurTexts(e) {
      const boolean = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!boolean) {
        this.$message.warning("请输入正整数");
        e.target.value = "";
      }
    },

    // 复选框
    handleSelectionChange(val) {
      this.deleteTables = val;
    },
    // 选择客户客户
    AddCustomer() {
      if (!this.readOnly) {
        this.dialogCustomer = true;
      }
    },
    // 新增样品检测
    addSampleDetection() {
      this.dialogDetectionItem = true;
    },
    // 复制样品检测
    copySampleDetection() {
      for (let i = 0; i < this.deleteTables.length; i++) {
        var data = JSON.parse(JSON.stringify(this.deleteTables[i]));
        data.index =
          this.formData.entrustSampleDetections[
            this.formData.entrustSampleDetections.length - 1
          ].index + 1;
        this.formData.entrustSampleDetections.push(data);
      }
    },
    // 删除样品检测
    deleteSampleDetection() {
      for (let o = 0; o < this.deleteTables.length; o++) {
        for (let i = 0; i < this.formData.entrustSampleDetections.length; i++) {
          if (
            this.deleteTables[o].index ===
            this.formData.entrustSampleDetections[i].index
          ) {
            this.formData.entrustSampleDetections.splice(i, 1);
          }
        }
      }
    },
    // 初始化
    async init() {
      // 查询委托领域
      getDictList({ dictCode: "EntrustDomain" }).then((res) => {
        this.entrustDomainData = res.data;
      });

      // 是否评价
      getDictList({ dictCode: "ReportConclusionType" }).then((res) => {
        this.reportConclusionTypeData = res.data;
      });

      // 报告形式
      getDictList({ dictCode: "ReportType" }).then((res) => {
        this.reportTypeList = res.data;
      });

      // 包装状态
      getDictList({ dictCode: "PackageStatus" }).then((res) => {
        this.packageStatusList = res.data;
      });

      // 样品处置
      getDictList({ dictCode: "SampleDispose" }).then((res) => {
        this.sampleDisposeList = res.data;
      });

      // 报告领取方式
      getDictList({ dictCode: "ReportGetType" }).then((res) => {
        this.reportGetTypeList = res.data;
      });

      // 委托取样
      getDictList({ dictCode: "EntrustSampleType" }).then((res) => {
        this.entrustSampleTypeList = res.data;
      });

      // editId 存在表示编辑 不存在表示新增
      this.title = this.readOnly
        ? "查看委托单"
        : this.editId
          ? "编辑委托单"
          : "新增委托单";
      // 获取委托单信息
      if (this.editId) {
        Get({ id: this.editId }).then((res) => {
          if (
            this.$refs.EntrustSampleDetection.sampleList === null ||
            this.$refs.EntrustSampleDetection.sampleList === undefined
          ) {
            this.$refs.EntrustSampleDetection.sampleList = [];
          }
          res.data.entrustOrderSamples.forEach((element) => {
            var samplingDataState = 0;
            this.$refs.EntrustSampleDetection.sampleList.push({
              id: element.id,
              sampleName: element.sampleName,
              sampleNum: element.sampleNum,
              sampleCount: element.sampleCount,
              originalSampleNumber: element.originalSampleNumber,
              brand: element.brand,
              samplingPosition: element.samplingPosition,
              capacity: element.capacity,
              sampleShape: element.sampleShape,
              sampleGrade: element.sampleGrade,
              manufacturer: element.manufacturer,
              numUseState: 0,
              samplingDataState: samplingDataState,
              inspectedAddress: element.inspectedAddress,
              sampleTypeName: element.sampleTypeName,
              tableData: [],
              detectionItemData: element.sysBusinessDetectionItems,
              entrustDetections: element.entrustDetections,
              inspectionBasis: element.inspectionBasis,
            });
            this.$refs.EntrustSampleDetection.detectionTableData(
              this.$refs.EntrustSampleDetection.sampleList.length - 1
            );
          });
          this.formData = res.data;
          this.getOrderNumberDto.entrustDomain = this.formData.entrustDomain;
        });
      }
    },
    // 提交表单
    submitForm: _.throttle(function(state, edit) {
      if (this.submitLoad) {
        this.submitLoad = false;
        this.formData.isEdit = edit;
        if (
          this.formData.entrustDomain === null ||
          this.getOrderNumberDto.entrustDomain === 0
        ) {
          this.$message.error("请选择委托类型！");
          this.submitLoad = true;
          return false;
        }

        if (state !== null && state !== "") {
          this.formData.orderStatusCode = state;
        }

        this.formData.sampleList = this.$refs.EntrustSampleDetection.sampleList;

        if (state !== 0) {
          if (
            this.formData.sampleList === null ||
            this.formData.sampleList.length === 0 ||
            this.formData.sampleList === undefined
          ) {
            this.$message.error("样品检测不能为空！");
            this.submitLoad = true;

            return false;
          }
          for (let i = 0; i < this.formData.sampleList.length; i++) {
            var item = this.formData.sampleList[i];
            if (
              item.detectionItemData.length === 0 ||
              item.detectionItemData === null ||
              item.detectionItemData === undefined
            ) {
              this.$message.error("请添加检测项目");
              this.submitLoad = true;

              return false;
            }

            if (item.sampleName === null || item.sampleName === "") {
              this.$message.error("样品名称不能为空");
              this.submitLoad = true;

              return false;
            }
            // if (item.sampleNum === null || item.sampleNum === "") {
            //   this.$message.error("样品编号不能为空");
            //   return false;
            // }
          }
          // 对象去重判断是否出现重复编号
          // const map = new Map();
          // var sampleCount = this.formData.sampleList.filter(
          //   (key) => !map.has(key.sampleNum) && map.set(key.sampleNum, 1)
          // );
          // if (sampleCount.length !== this.formData.sampleList.length) {
          //   this.$message.error("不能出现重复样品编号");
          //   return false;
          // }
        }
        // 校验表单必填项
        this.$refs.formData.validate((valid) => {
          if (valid) {
            if (this.editId) {
              this.formData.isEdit = true;
              this.editAPI();
            } else {
              // 新增
              this.addAPI();
            }
          } else {
            this.$message.error("请完善信息！");
            this.submitLoad = true;
          }
        });
      }
    }, 2000),
    // 新增接口
    addAPI() {
      Create(this.formData)
        .then((res) => {
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = true;
        });
    },
    // 编辑接口
    editAPI() {
      Update(this.formData)
        .then((res) => {
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = true;
        });
    },
    // 操作成功回调用
    SuccessfulOperation() {
      this.submitLoad = true;
      // this.$message.success('操作成功');
      this.$emit("success");
      this.handleClose();
    },
    // 关闭弹框
    handleClose() {
      this.$emit("update:dialogFormVisible", false);
      this.$emit("update:editId", "");
      this.$emit("closeDialog");
    },
    // 关闭弹框动画结束
    closedDialog() {
      this.formData.entrustSampleAddress = "";
      this.formData.entrustDomain = "";
      this.formData.reportGetTypeRemake = "";
      this.formData.packageStatusRemake = "";
      this.formData.entrustSampleDetections = [];
      this.formData.accessoryData = [];
      this.deleteTables = [];
      this.fileCount = 0;
      // 动画结束后在清空表单 防止页面闪烁
      this.$refs.formData.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.chioseFileDiv {
  background-color: #f1f8ff;
  height: 45px;
  line-height: 45px;
}
.addCustomer {
  width: 30px;
  color: white;
  font-size: 20px;
  height: 32px;
  text-align: center;
  border-radius: 5px;
  border: 1px silver;
  background-color: #4787ff;
  position: absolute;
  top: 0px;
  right: 0px;
}

.card-field-label {
  display: block;
  width: 100%;
  height: 16px;
  font-size: 0;
  text-align: left;
  margin-bottom: 6px;
  padding-left: 6px;

  span {
    font-family: "Microsoft YaHei";
    color: #da1c76;
    line-height: 16px;
    font-size: 12px;
  }
}
</style>
